using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Demo
{
    public interface IApplicationBuilder
    {
        IServiceProvider ApplicationServices { get; set; }
        IFeatureCollection ServerFeatures { get; set; }
        void Use(Func<RequestDelegate, RequestDelegate> middleware);
        RequestDelegate Build();
    }
    public class ApplicationBuilder : IApplicationBuilder
    {
        public ApplicationBuilder(IServiceProvider serviceProvider, IFeatureCollection serverFeatures)
        {
            ApplicationServices = serviceProvider;
            ServerFeatures = serverFeatures;

        }
        private IList<Func<RequestDelegate, RequestDelegate>> middlewareList = new List<Func<RequestDelegate, RequestDelegate>>();

        private RequestDelegate Last = (context) =>
        {
            return Task.CompletedTask;
        };

        public IServiceProvider ApplicationServices { get; set; }

        public IFeatureCollection ServerFeatures { get; set; }
        public void Use(Func<RequestDelegate, RequestDelegate> middleware)
        {
            middlewareList.Add(middleware);
        }

        public RequestDelegate Build()
        {
            RequestDelegate requestDelegate = Last;
            foreach (var item in middlewareList.Reverse())
            {
                requestDelegate = item(requestDelegate);
            }
            return requestDelegate;
        }
    }
}